/*
 *
 * Copyright (c) 2023 - future
 * @author fzh
 * @email e_341877120_mail@163.com
 * @link https://mvnrepository.com/search?q=io.github.xrfzh.cn
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package cn.xrfzh.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.xrfzh.common.axios.AxiosEnum;
import cn.xrfzh.common.axios.AxiosResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Objects;
import java.util.Set;

/**
 * 自定义全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class MyGlobalExceptionHandler {

    /**
     * 处理系统未知异常
     */
    @ExceptionHandler(Exception.class)
    public AxiosResult handle(Exception e, HttpServletRequest request) {
        printLogOfRequest(request, e);
        log.error(e.getMessage());
        return AxiosResult.error(AxiosEnum.UNKNOWN_ERROR);
    }

    /**
     * 处理运行时发生的或主动抛出的其他自定义异常（继承于RuntimeException）
     */
    @ExceptionHandler(MyCustomException.class)
    public AxiosResult handle(MyCustomException e, HttpServletRequest request) {
        printLogOfRequest(request, e);
        log.error(e.getMessage());
        return AxiosResult.error(e.getMessage());
    }

    /**
     * 处理字段值重复(违背唯一约束条件)的SQL异常
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public AxiosResult handle(SQLIntegrityConstraintViolationException e, HttpServletRequest request) {
        printLogOfRequest(request, e);
        log.error(e.getMessage());
        if (e.getMessage().contains("Duplicate entry")) {
            return AxiosResult.error(AxiosEnum.UNIQUE_ERROR);
        }
        return AxiosResult.error(AxiosEnum.UNKNOWN_ERROR);
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public AxiosResult handle(NullPointerException e, HttpServletRequest request) {
        printLogOfRequest(request, e);
        log.error(e.getMessage());
        return AxiosResult.error(AxiosEnum.NULL_POINTER_ERROR);
    }

    /**
     * 拦截不合法声明异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public AxiosResult handle(IllegalArgumentException e, HttpServletRequest request) {
        printLogOfRequest(request, e);
        log.error(e.getMessage());
        return AxiosResult.error(AxiosEnum.PARAMETER_ERROR.getMsg(), e.getMessage());
    }

    /**
     * 拦截缺少参数异常
     *
     * @param ex
     * @param request
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public AxiosResult handle(MissingServletRequestParameterException ex, HttpServletRequest request) {
        printLogOfRequest(request, ex);
        log.error(ex.getCause().getLocalizedMessage());
        return AxiosResult.error(AxiosEnum.PARAMETER_ERROR.getMsg(), "缺少必要参数，参数名称为" + ex.getParameterName());
    }

    /**
     * 拦截controller方法参数上直接添加校验注解产生的的异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public AxiosResult handle(ConstraintViolationException e, HttpServletRequest request) {
        printLogOfRequest(request, e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();
        log.error(message);
        return AxiosResult.error(AxiosEnum.PARAMETER_ERROR.getMsg(), message);
    }

    /**
     * 拦截get请求参数校验抛出的异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(BindException.class)
    public AxiosResult handle(BindException e, HttpServletRequest request) {
        printLogOfRequest(request, e);
        // 获取异常中随机一个异常信息
        String defaultMessage = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        log.error(defaultMessage);
        return AxiosResult.error(AxiosEnum.PARAMETER_ERROR.getMsg(), defaultMessage);
    }

    /**
     * 拦截处理请求参数格式错误产生的异常
     * （@RequestBody加上validate失败后抛出的异常是MethodArgumentNotValidException异常）
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AxiosResult handle(MethodArgumentNotValidException e, HttpServletRequest request) {
        printLogOfRequest(request, e);
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        log.error(message);
        return AxiosResult.error(AxiosEnum.PARAMETER_ERROR.getMsg(), message);
    }

    /**
     * 拦截参数类型转换错误产生的异常
     *
     * @param exception
     * @param request
     * @return
     */
    @ExceptionHandler(HttpMessageConversionException.class)
    public AxiosResult handle(HttpMessageConversionException exception, HttpServletRequest request) {
        printLogOfRequest(request, exception);
        log.error(exception.getCause().getLocalizedMessage());
        return AxiosResult.error(AxiosEnum.PARAMETER_ERROR);
    }

    /**
     * Token无效或不存在
     *
     * @param exception
     * @param request
     * @return
     */
    @ExceptionHandler(NotLoginException.class)
    public AxiosResult handle(NotLoginException exception, HttpServletRequest request) {
        printLogOfRequest(request, exception);
        log.error(exception.getMessage());
        return AxiosResult.error("Token无效或不存在");
    }

    /**
     * 接口权限不足
     *
     * @param exception
     * @param request
     * @return
     */
    @ExceptionHandler(NotPermissionException.class)
    public AxiosResult handle(NotPermissionException exception, HttpServletRequest request) {
        printLogOfRequest(request, exception);
        log.error(exception.getMessage());
        return AxiosResult.error("接口权限不足");
    }

    /**
     * 定义打印请求日志方法
     *
     * @param request
     * @param e
     */
    private void printLogOfRequest(HttpServletRequest request, Exception e) {
        if (null != request) {
            log.error("请求方法：{}，请求地址：{}，程序异常：{}", request.getMethod(), request.getRequestURL(), e);
        } else {
            log.error("程序异常：", e);
        }
    }

}
